package com.qf.lja.servlet;


import com.qf.lja.dao.ProductDao;
import com.qf.lja.enity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet(urlPatterns = "/ProductPage.do")
public class ProductPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String pageSize = req.getParameter("pageSize");
        String currentPage = req.getParameter("currentPage");
        System.out.println("deBug");
        int pageSizeInt = 8;
        if(pageSize != null && !"".equals(pageSize)) {
            pageSizeInt = Integer.parseInt(pageSize);
            if(pageSizeInt < 1 || pageSizeInt > 100) {
                pageSizeInt = 10;   // 超出页面范围就设置默认值
            }
        }

        int currentPageInt = 1; // 当前页数
        ProductDao productDao = new ProductDao(); // 替换为适合产品的 DAO
        int rows = productDao.countProducts(); // 获取产品总数
        int totalPage = (int)Math.ceil(1.0 * rows / pageSizeInt); // 计算总页数
        if(currentPage != null && !"".equals(currentPage)) {
            currentPageInt = Integer.parseInt(currentPage);
            if(currentPageInt < 1 || currentPageInt > totalPage) {
                currentPageInt = 1; // 当前页超出范围，使用默认值
            }
        }

        List<Product> productList = productDao.getProductsPage(currentPageInt, pageSizeInt); // 获取分页产品列表

        req.setAttribute("pageSize", pageSizeInt);
        req.setAttribute("totalPage", totalPage);
        req.setAttribute("currentPage", currentPageInt);
        req.setAttribute("productList", productList); // 设置产品列表属性

        //打印参数方便
        System.out.println("pageSize:"+pageSize);
        System.out.println("currentPage:"+currentPage);
        System.out.println("rows:"+rows);
        System.out.println("totalPage:"+totalPage);

        req.getRequestDispatcher("/goodsList.jsp").forward(req, resp); // 转发到产品列表页面
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
